import React, { useEffect, useRef, useState } from "react";

function App() {
  const localVideoRef = useRef(null); // 本地视频
  const remoteVideoRef = useRef(null); // 远程视频
  const [socket, setSocket] = useState(null); // WebSocket 实例
  const [peerConnection, setPeerConnection] = useState(null); // RTCPeerConnection 实例

  useEffect(() => {
    // 初始化 WebSocket 连接
    const ws = new WebSocket("ws://localhost:8080");
    setSocket(ws);

    // 初始化 RTCPeerConnection
    const pc = new RTCPeerConnection({
      iceServers: [
        { urls: "stun:stun.l.google.com:19302" }, // STUN 服务器
      ],
    });

    // 监听 ICE 候选信息
    pc.onicecandidate = (event) => {
      if (event.candidate) {
        ws.send(JSON.stringify({ type: "candidate", candidate: event.candidate }));
      }
    };

    // 监听远程流
    pc.ontrack = (event) => {
      if (remoteVideoRef.current) {
        remoteVideoRef.current.srcObject = event.streams[0];
      }
    };

    setPeerConnection(pc);

    // 监听 WebSocket 消息
    ws.onmessage = async (event) => {
      const message = JSON.parse(event.data);

      if (message.type === "offer") {
        await pc.setRemoteDescription(new RTCSessionDescription(message));
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);
        ws.send(JSON.stringify({ type: "answer", sdp: pc.localDescription }));
      } else if (message.type === "answer") {
        await pc.setRemoteDescription(new RTCSessionDescription(message));
      } else if (message.type === "candidate") {
        await pc.addIceCandidate(new RTCIceCandidate(message.candidate));
      }
    };

    // 获取本地媒体流
    navigator.mediaDevices
      .getUserMedia({ video: true, audio: true })
      .then((stream) => {
        if (localVideoRef.current) {
          localVideoRef.current.srcObject = stream;
        }

        // 添加本地流到 PeerConnection
        stream.getTracks().forEach((track) => pc.addTrack(track, stream));
      })
      .catch((err) => console.error("Error accessing media devices.", err));

    return () => {
      ws.close();
      pc.close();
    };
  }, []);

  // 创建 Offer
  const createOffer = async () => {
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);
    socket.send(JSON.stringify({ type: "offer", sdp: peerConnection.localDescription }));
  };

  return (
    <div>
      <h1>Video Communication</h1>
      <div>
        <video ref={localVideoRef} autoPlay muted style={{ width: "45%", margin: "10px" }} />
        <video ref={remoteVideoRef} autoPlay style={{ width: "45%", margin: "10px" }} />
      </div>
      <button onClick={createOffer}>Start Call</button>
    </div>
  );
}

export default App;